package com.ms.module.wechat.clear.utils;

import android.content.Context;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 清除语音临时文件
 */
public class ClearTempFileUtils {

    private static List<String> result = new ArrayList<>();

    /**
     * 检索 文件
     *
     * @param path
     */
    private static void search(String path) {
        if (path == null || "".equals(path)) {
            return;
        }

        File file = new File(path);

        File[] files = file.listFiles();

        for (File it : files) {

            if (it.isHidden()) {
                continue;
            }
            if (it.isDirectory()) {
                search(it.getPath());
            }

            if (it.getName().endsWith("out.mp3") || it.getName().endsWith("out.pcm")) {
                result.add(it.getPath());
            }
        }
    }


    /**
     * 清除编码的临时 音频 文件
     *
     * @param context
     */
    public static void clear(Context context) {

        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Exception {
                result.clear();
                search("/sdcard/Android/data/" + context.getPackageName() + "/wechatclear/");

                for (String it : result) {
                    File file = new File(it);
                    if (file.exists()) {
                        file.delete();
                    }
                }
            }
        }).subscribeOn(Schedulers.io())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull String s) {

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}